package com.skz.job.web;

import com.skz.job.domain.Job;
import com.skz.job.service.JobService;
import com.skz.job.vo.JobMapVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 宋开宗
 * @create: 2019-02-19 14:15
 **/
@RestController
@RequestMapping("/job/boss")
public class BossJobController {
    @Autowired
    private JobService jobService;

    @GetMapping
    public ResponseEntity search(@RequestParam(required = false) String queryKeywords,
                                 @RequestParam(required = false) String deleteKeywords) {
        String[] queryArray = new String[0];
        String[] deleteArray = new String[0];
        if (!StringUtils.isEmpty(queryKeywords)) {
            queryArray = queryKeywords.toUpperCase().replaceAll("，", ",").split(",");
        }
        if (!StringUtils.isEmpty(deleteKeywords)) {
            deleteArray = deleteKeywords.toUpperCase().replaceAll("，", ",").split(",");
        }
        List<Job> jobs = jobService.findTodayJobs();
        List<JobMapVO> jobMapVOS = new ArrayList<>();
        for (Job job : jobs) {
            String searchStr = (job.getCompanyName() + job.getAddress() + job.getDescription() + job.getDistrict()).replaceAll(" ", "").toUpperCase();
            boolean hasQueryWords = true;
            for (int i = 0; i < queryArray.length; i++) {
                if (!searchStr.contains(queryArray[i])) {
                    hasQueryWords = false;
                    break;
                }
            }
            if (hasQueryWords) {
                boolean hasDeleteWords = false;
                for (int i = 0; i < deleteArray.length; i++) {
                    if (searchStr.contains(deleteArray[i])) {
                        hasDeleteWords = true;
                        break;
                    }
                }
                if (!hasDeleteWords) {
                    jobMapVOS.add(new JobMapVO(job.getCompanyName(), job.getLongitude(), job.getUrl()));
                }
            }
        }
        return ResponseEntity.ok(jobMapVOS);
    }

    @PostMapping
    public ResponseEntity save() {
        jobService.findTodayJobs().forEach(job -> jobService.del(job));
        jobService.save();
        return ResponseEntity.ok("success");
    }
}
